package com.leemon.mall.sys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.leemon.mall.sys.constant.SysConstant;
import com.leemon.mall.sys.model.SysMenu;
import com.leemon.mall.sys.dao.SysMenuMapper;
import com.leemon.mall.sys.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单管理 服务实现类
 * </p>
 *
 * @author leemon
 * @since 2019-09-04
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenu> listMenuByUserId(Long userId) {
        List<SysMenu> sysMenus = null;
        if (userId == SysConstant.SUPER_ADMIN_ID) {
            sysMenus = sysMenuMapper.listMenu();
        } else {
            sysMenus = sysMenuMapper.listMenuByUserId(userId);
        }
        //为菜单归类，
        Map<Long, List<SysMenu>> listMap =
                sysMenus.stream()
                        .sorted(Comparator.comparing(SysMenu::getOrderNum))
                        .collect(Collectors.groupingBy(SysMenu::getParentId));

        //系统目录（一级菜单）
        List<SysMenu> sysRootMenu = listMap.get(0L);
        if (CollectionUtil.isEmpty(sysRootMenu)) {
            return Collections.emptyList();
        }

        //系统菜单（二级菜单）
        for (SysMenu sysMenu : sysRootMenu) {
            sysMenu.setList(listMap.get(sysMenu.getMenuId()));
        }

        return sysRootMenu;
    }
}
